package com.u.social.chat.handler;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: awesome-spring
 * @description: 聊天处理器类
 * @author: Alex Wu
 * @createDate: 2025-03-14 16:10
 **/
public class AuthMsgChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final Map<String, Channel> userChannelMap = new ConcurrentHashMap<>();
    private static final Map<Channel, String> channelUsers = new ConcurrentHashMap<>();
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String text = textWebSocketFrame.text();

        JSONObject json = JSONObject.parseObject(text);

        if("auth".equals(json.get("type"))){
            String userId = json.getString("userId");
            userChannelMap.put(userId, channelHandlerContext.channel());

            channelUsers.put(channelHandlerContext.channel(), userId);


        }else if("message".equals(json.get("type"))){
            String targetUserId = json.getString("toUserId");
            String message = json.getString("message");

            Channel targetChannel = userChannelMap.get(targetUserId);

            if(targetChannel != null){
                targetChannel.writeAndFlush(new TextWebSocketFrame("Echo: "+ message));
            }else{
                System.out.println("User " + targetUserId + " not online.");
            }
        }
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        System.out.println("连接了" + ctx.channel().id());
//        userChannelMap.put(ctx.channel().id().asShortText(), ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        System.out.println("检测到断开连接了" + ctx.channel().id());
        String userId = channelUsers.remove(ctx.channel());
        if(userId != null){
            userChannelMap.remove(userId);
        }
    }
}
